import * as Blockly from 'blockly/core';

export const LNSF_AIoTLOGO = function (_, generator) {
    generator = generator ?? Blockly.Python;
    generator.definitions_['include_' + 'zhushi'] = '/*****\n技术支持：关注微信公众号【人工智能素养教育共同体】\n******/';
    generator.definitions_['include_' + 'taobaodian'] = '/*****\n https://shop221040643.taobao.com \n******/';
    var code = '';
    return code;
}

export const UARTInit = function (_, generator) {
    generator = generator ?? Blockly.Python;
    var dropdown_UART = this.getFieldValue('UART');
    var dropdown_RXPIN = this.getFieldValue('RXPIN');
    var dropdown_TXPIN = this.getFieldValue('TXPIN');
    var dropdown_BAUNT = this.getFieldValue('BAUNT');
    generator.definitions_['import_' + 'time'] = 'import time';
    generator.definitions_['import_' + 'machine'] = 'import machine';
    var code = '\nuart'
        + dropdown_UART
        +' = machine.UART('
        + dropdown_UART
        + ', baudrate='
        + dropdown_BAUNT
        + ', tx='
        + dropdown_TXPIN
        + ', rx='
        + dropdown_RXPIN
        + ')\n';
    return code;
}

export const LoRaInit = function (_, generator) {
    generator = generator ?? Blockly.Python;
    var dropdown_UART = this.getFieldValue('UART');
    var number_CHANNEL = this.getFieldValue('CHANNEL');
    var number_LOCAL_GROUP = this.getFieldValue('LOCAL_GROUP');
    var number_LOCAL_ADDR = this.getFieldValue('LOCAL_ADDR');
    var number_TARGET_GROUP = this.getFieldValue('TARGET_GROUP');
    var number_TARGET_ADDR = this.getFieldValue('TARGET_ADDR');
    var dropdown_SPEED = this.getFieldValue('SPEED');
    var dropdown_RATE = this.getFieldValue('RATE');
    generator.definitions_['import_' + 'time'] = 'import time';
    generator.definitions_['import_' + 'machine'] = 'import machine';
    var code = '\ndef calculateXOR(data):\n    result = 0\n    for d in data:\n        result ^= d\n    return result\ndef decimalToHexBytes(decimalData):\n    bohexData = bytearray(4)\n    for i in range(4):\n        bohexData[i] = (decimalData >> (8 * (3 - i))) & 0xFF\n    return bohexData\n'
        + 'def intToBinary(number, length):\n    binaryString = ""\n    for i in range(length):\n        binaryString = str(number % 2) + binaryString\n        number //= 2\n    return binaryString\n'
        + 'def DecimalToHex(moshidata):\n    moshihexData = bytearray(2)\n    moshihexData[0] = (moshidata >> 8) & 0xFF\n    moshihexData[1] = moshidata & 0xFF\n    return moshihexData\ndef transparent(type1, baud1, airspeed1, power1, channel1, local_group_number1, local_group_addr1, target_group_number1, target_group_addr1, uart):\n    transparentdata = [(channel1), (power1), (airspeed1)]\n    type1addresses = [(local_group_number1), (local_group_addr1), (target_group_number1), (target_group_addr1)]\n    baud1hexData = decimalToHexBytes(baud1)\n    mode1binaryData = intToBinary(transparentdata[0], 7) + intToBinary(transparentdata[1], 2) + intToBinary(transparentdata[2], 3)\n    mode1hexValue = int(mode1binaryData, 2)\n    parameter1hexData = bytearray(2)\n    parameter1hexData[0] = (mode1hexValue >> 8)\n    parameter1hexData[1] = mode1hexValue & 0xFF\n    type1hexData = DecimalToHex(type1)\n    head = bytearray([0xAF, 0xAF, 0x55, 0x55, 0x5A, 0x7F, 0x80, 0x04, 0x1E])\n    jiaoyan = bytearray([0x00])\n    guding1 = bytearray([0x05, 0x03, 0xE8])\n    zhuji = bytearray([0x00])\n    guding2 = bytearray([0x77, 0x77, 0x77, 0x2E, 0x61, 0x73, 0x68, 0x69, 0x6E, 0x69, 0x6E, 0x67, 0x2E, 0x63, 0x6F, 0x6D, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x05, 0x50, 0x00, 0x23, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x00, 0x0A, 0x19, 0x00, 0x80])\n    otherpara1 = bytearray([0, 0, 0, 0, 23, 2])\n'
        + '    trailer = bytearray([0x50, 0x50, 0xAA, 0xAA, 0xA5, 0x0D, 0x0A])\n    storedHexData = bytearray()\n    for b in head:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    for b in baud1hexData:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    uart.write(jiaoyan)\n    storedHexData.extend(jiaoyan)\n    for b in parameter1hexData:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    for b in type1hexData:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    for b in guding1:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    uart.write(zhuji)\n    storedHexData.extend(zhuji)\n    for b in guding2:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    for b in type1addresses:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    for b in otherpara1:\n        uart.write(bytes([b]))\n        storedHexData.append(b)\n    sum_val = sum(storedHexData)\n    xorResult = calculateXOR(storedHexData)\n    lowByte = sum_val & 0xFF\n    uart.write(bytes([lowByte]))\n    uart.write(bytes([xorResult]))\n    for b in trailer:\n        uart.write(bytes([b]))\n    time.sleep(1)\n'
        + '\ntransparent(1, 9600, '
        + dropdown_SPEED
        + ', '
        + dropdown_RATE
        + ', '
        + number_CHANNEL
        + ', '
        + number_LOCAL_GROUP
        + ', '
        + number_LOCAL_ADDR
        + ', '
        + number_TARGET_GROUP
        + ', '
        + number_TARGET_ADDR
        + ', '
        + dropdown_UART
        + ')\n';
    return code;
}

export const LEDDISPLAY = function () {
    var value_LEDdisplayvalue = Blockly.Python.valueToCode(this, 'LEDdisplayvalue', Blockly.Python.ORDER_ATOMIC);
    var dropdown_UART = this.getFieldValue('UART');
    var dropdown_DATA = this.getFieldValue('DATA');
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    var code = '\nled_show_number('
        + dropdown_DATA
        + ', '
        + value_LEDdisplayvalue
        + ', 1, '
        + dropdown_UART
        + ')\n';
    return code;
};
export const LEDDISPLAY1 = function () {
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    var code = '\ndef crc16_modbus(ptr, len):\n    crc = 0xFFFF\n    for i in range(len):\n        crc ^= ptr[i]\n        for j in range(8):\n            if crc & 1:\n                crc >>= 1\n                crc ^= 0xA001\n            else:\n                crc >>= 1\n    return crc\ndef led_show_number(wdRegAddress, Value, ledaddr, uart):\n    cmd = bytearray(13)\n    cmd[0] = ledaddr\n    cmd[1] = 0x10\n    cmd[2] = wdRegAddress >> 8\n    cmd[3] = wdRegAddress & 0xff\n    cmd[4] = 0\n    cmd[5] = 2\n    cmd[6] = 4\n    if wdRegAddress in [1,7,9, 11]:\n        cmd[7:11] = struct.pack(\'>i\', int(Value))\n    elif wdRegAddress in [9304,2,3,4,5,6,8,10]:\n        cmd[7:11] = struct.pack(\'>f\', float(Value))\n    crc = crc16_modbus(cmd, 11)\n    cmd[11] = crc & 0xff\n    cmd[12] = crc >> 8\n    uart.write(cmd)\n';
    return code;
};

export const SOIL0 = function () {
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_soil_num_ShiDu = 0\nLNSFAIoT_soil_num_WenDu = 0\nLNSFAIoT_soil_num_PH = 0\nLNSFAIoT_soil_num_N = 0\nLNSFAIoT_soil_num_P = 0\nLNSFAIoT_soil_num_K = 0\nLNSFAIoT_soil_num_DianDaoLv = 0\nSerialReciveData_soil = [0] * 30\nwenxunsoil = bytearray([0x02, 0x03, 0x00, 0x00, 0x00, 0x07, 0x04, 0x3B])\ndef LNSFAIoT_soil_enquiry(addr,uart2):\n    global soiladdr, SerialReciveData_soil\n    time.sleep(0.8)\n    wenxunsoil[0] = addr & 0xFF\n    for i in wenxunsoil:\n        uart2.write(bytes([i]))\n    time.sleep(0.2)\n    SerialReciveData_soil = bytearray(40)\n    len_ = 0\n    while uart2.any():\n        byte = uart2.read(1)\n        if byte:\n            SerialReciveData_soil[len_] = byte[0]\n            len_ += 1\n    if SerialReciveData_soil[0] == 0x02:\n        global LNSFAIoT_soil_num_ShiDu,LNSFAIoT_soil_num_WenDu,LNSFAIoT_soil_num_DianDaoLv,LNSFAIoT_soil_num_PH,LNSFAIoT_soil_num_N,LNSFAIoT_soil_num_P,LNSFAIoT_soil_num_K\n        data_bytes = SerialReciveData_soil[3:len(SerialReciveData_soil)-2]\n        data_list = []\n        i = 0\n        while i + 1 < len(data_bytes):\n            data_list.append(data_bytes[i] << 8 | data_bytes[i + 1])\n            i = i + 2\n        # print("data_list ({}): ".format(len(data_list)), data_list)\n        LNSFAIoT_soil_num_ShiDu = data_list[0] / 10.0\n        LNSFAIoT_soil_num_WenDu =  data_list[1] / 10.0\n        LNSFAIoT_soil_num_DianDaoLv =  data_list[2]\n        LNSFAIoT_soil_num_PH =  data_list[3] / 10.0\n        LNSFAIoT_soil_num_N = data_list[4]\n        LNSFAIoT_soil_num_P = data_list[5]\n        LNSFAIoT_soil_num_K = data_list[6]\ndef LNSFAIoT_soil_println():\n    print("多合一土壤参数:")\n    print("土壤温度：" + str(LNSFAIoT_soil_num_WenDu) + " ℃")\n    print("土壤湿度/水分/含水率：" + str(LNSFAIoT_soil_num_ShiDu) + " %")\n    print("土壤电导率：" + str(LNSFAIoT_soil_num_DianDaoLv) + " us/cm")\n    print("土壤PH：" + str(LNSFAIoT_soil_num_PH))\n    print("土壤氮元素：" + str(LNSFAIoT_soil_num_N) + " us/cm")\n    print("土壤磷元素：" + str(LNSFAIoT_soil_num_P) + " us/cm")\n    print("土壤钾元素：" + str(LNSFAIoT_soil_num_K) + " us/cm")\n';
    return code;
};

export const SOIL1 = function () {
    var dropdown_UART = this.getFieldValue('UART');
    var number_SOILADDR = this.getFieldValue('SOILADDR');
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_soil_enquiry('
        + number_SOILADDR
        + ', '
        + dropdown_UART
        + ')\n';
    return code;
};
export const SOIL2 = function (_, generator) {
    generator = generator ?? Blockly.Python;
    generator.definitions_['import_' + 'struct'] = 'import struct';
    generator.definitions_['import_' + 'machine'] = 'import machine';
    generator.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_soil_println()\n';
    return code;
}

export const SOIL3 = function () {
    var dropdown_SOILDATA = this.getFieldValue('SOILDATA');
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    var code = dropdown_SOILDATA;
    return [code, Blockly.Python.ORDER_ATOMIC];
};
export const weather0 = function () {
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_num_windspeed = 0\nLNSFAIoT_num_light = 0\nLNSFAIoT_num_rain = 0\nLNSFAIoT_num_airpressure = 0\nLNSFAIoT_num_windpower = 0\nLNSFAIoT_num_winddirection_angle = 0\nLNSFAIoT_num_winddirection_gear = 0\nwenurxunweather = bytearray([0x03, 0x03, 0x01, 0xf4, 0x00, 0x0e, 0x85, 0xe2])\nSerialReciveData_weather = bytearray(50)\ndef LNSFAIoT_weather_enquiry(addr, uart2):\n    time.sleep(0.8)\n    wenurxunweather[0] = addr & 0xFF\n    for i in wenurxunweather:\n        uart2.write(bytes([i]))\n    time.sleep(0.2)\n    SerialReciveData_weather = bytearray(40)\n    len_ = 0\n    while uart2.any():\n        byte = uart2.read(1)\n        if byte:\n            SerialReciveData_weather[len_] = byte[0]\n            len_ += 1\n    if SerialReciveData_weather[0] == 0x03:\n        #print(4)\n        global LNSFAIoT_num_windspeed, LNSFAIoT_num_windpower, LNSFAIoT_num_winddirection_gear, LNSFAIoT_num_winddirection_angle, LNSFAIoT_num_airpressure, LNSFAIoT_num_light, LNSFAIoT_num_rain\n        data_bytes = SerialReciveData_weather[3:len(SerialReciveData_weather)-2]\n        data_list = []\n        i = 0\n        while i + 1 < len(data_bytes):\n            data_list.append(data_bytes[i] << 8 | data_bytes[i + 1])\n            i = i + 2\n        #print("data_list ({}): ".format(len(data_list)), data_list)\n        LNSFAIoT_num_windspeed = data_list[0] / 100.0\n        LNSFAIoT_num_windpower =  data_list[1]\n        LNSFAIoT_num_winddirection_gear =  data_list[2]\n        LNSFAIoT_num_winddirection_angle =  data_list[3]\n        LNSFAIoT_num_airpressure = data_list[9] / 10.0\n        LNSFAIoT_num_light = data_list[12]\n        LNSFAIoT_num_rain = data_list[13]\ndef LNSFAIoT_weather_println():\n    print("多合一气象参数:")\n    print("风速：" + str(LNSFAIoT_num_windspeed) + " m/s")\n    print("风力：" + str(LNSFAIoT_num_windpower))\n    print("风向(档位)：" + str(LNSFAIoT_num_winddirection_gear))\n    print("风向：" + str(LNSFAIoT_num_winddirection_angle) + " °")\n    print("大气压力：" + str(LNSFAIoT_num_airpressure) + " Kpa")\n    print("光照：" + str(LNSFAIoT_num_light) + " 百Lux")\n    print("雨量：" + str(LNSFAIoT_num_rain) + " mm")\n';
    return code;
};
export const weather1 = function () {
    var dropdown_UART = this.getFieldValue('UART');
    var number_weatheraddr = this.getFieldValue('weatheraddr');
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_weather_enquiry('
            + number_weatheraddr
            + ', '
            + dropdown_UART
            + ')\n';
    return code;
};


export const weather2 = function (_, generator) {
    generator = generator ?? Blockly.Python;
    generator.definitions_['import_' + 'struct'] = 'import struct';
    generator.definitions_['import_' + 'machine'] = 'import machine';
    generator.definitions_['import_' + 'time'] = 'import time';
    var code = '\nLNSFAIoT_weather_println()\n';
    return code;
}

export const weather3 = function () {
    var dropdown_WEATHERDATA = this.getFieldValue('WEATHERDATA');
    Blockly.Python.definitions_['import_' + 'struct'] = 'import struct';
    Blockly.Python.definitions_['import_' + 'machine'] = 'import machine';
    Blockly.Python.definitions_['import_' + 'time'] = 'import time';
    // var code = '\nLNSFAIoT_num_weatherdata('
    //     + dropdown_WEATHERDATA
    //     + ')\n';
    var code = dropdown_WEATHERDATA;
    return [code, Blockly.Python.ORDER_ATOMIC];
};

export const TDS = function () {
    var dropdown_TDSPIN = this.getFieldValue('TDSPIN');
    var code = 'machine.ADC(machine.Pin('
        + dropdown_TDSPIN
        + ')).read_u16()';
    return [code, Blockly.Python.ORDER_ATOMIC];
};